package com.example.springblog.controller;

import com.example.springblog.constant.Constants;
import com.example.springblog.model.Result;
import com.example.springblog.model.UserInfo;
import com.example.springblog.service.UserService;
import com.example.springblog.utils.JwtUtils;
import com.example.springblog.utils.SecurityUtils;
import io.jsonwebtoken.lang.Strings;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String userName, String password){
        log.info("UserController#login接收到参数 ：userName = {}，password = {}",userName,password);
        //1. 参数合法性校验
        //2. 校验密码是否正确
        //3. 密码正确，返回token
        //4. 密码错误，返回错误信息
        if(!Strings.hasLength(userName) || !Strings.hasLength(password)){
            log.error("账号或密码不能为空");
            return Result.fail("账号或密码不能为空");
        }

        //第一层校验通过
        //从数据库中查找用户
        UserInfo userInfo = userService.selectByName(userName);
        //用户不存在
        if(userInfo == null){
            log.error("用户不存在");
            return Result.fail("用户不存在");
        }
        //密码错误
        if(!SecurityUtils.verify(password,userInfo.getPassword())){
            log.error("密码错误");
            return Result.fail("密码错误");
        }
        //密码正确，生成并返回token


        log.info("即将根据前端输入登录信息，生成载荷或者校验token...");
        Map<String,Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID,userInfo.getId());
        claim.put(Constants.TOKEN_USERNAME,userName);
        //这个不能加进去，隐私信息claim.put("password",userInfo.getPassword());
        String token = JwtUtils.genJwtToken(claim);
        log.info("UserController#login 返回结果token：{}",token);
        return Result.success(token);
    }


    /**
     * 获取当前登录用户的信息
     *
     */
    @RequestMapping("/getUserInfo")
    public UserInfo getLoginUserInfo(HttpServletRequest request){
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        Integer userId =  JwtUtils.getIdByToken(token);
        if(userId == null){
            log.info("用户未登录");
            return null;
        }
        UserInfo userInfo = userService.selectById(userId);
        return userInfo;
    }

    /**
     * 根据博客id，获取作者信息
     *
     */
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){

        if(blogId <= 0){
            return null;
        }
        UserInfo userInfo = userService.getAuthorInfo(blogId);
        return userInfo;

    }

}
